<template>
  <!-- 发票登记 -->
  <div>
    <!-- 搜索框 -->
    <TopFilter ref="topFilterForm" :list="topFilterList" :cols="3" :labelWidth="110" :collapse="false" @filterChange="changeHandle"></TopFilter>
    <!-- 列表展示 -->
    <FilterTable
      ref="table"
      :columns="columns"
      :datakey="'rows'"
      :fetchapi="fetchApi"
      :params="fetchParams"
      columnsRef="lxjczclglinvoiceRegisterTable"
      selectionType="single"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="columns => (this.selectColumns = columns)"
      :onSyncTableData="getAll"
    >
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" :disabled="exportAble" @click="exportTable">导出</el-button>
      </template>
    </FilterTable>
    <div class="vehicle-details-wrap">
      <div class="box">
        <FormPanel ref="feesPaidPanel" :list="feesSettlementList" :cols="4" :labelWidth="150" :isSubmitBtn="false" />
      </div>
      <ButtonArea :style="{ justifyContent: 'center' }">
        <!-- <el-button
          type="primary"
          icon="el-icon-document"
          @click="saveInvoiceInfo"
          :disabled="saveInvoiceAble"
        >保存</el-button>-->
        <el-button type="primary" icon="el-icon-plus" @click="registerClick">登记</el-button>
        <el-button type="primary" icon="el-icon-document" :disabled="this.selectColumns[0] && this.selectColumns[0].INVOICE_NO ? false : true" @click="cancelRegister">取消登记</el-button>
        <!-- <el-button
          type="primary"
          icon="el-icon-download"
          @click="exportTable"
          :disabled="exportAble"
        >导出</el-button>-->
      </ButtonArea>
    </div>

    <!-- 选择客户 -->
    <BaseDialog title="客户选择" :modal="true" :visible.sync="showCustomerDealer">
      <Customer @saveDialog="getCustomerInfo" @close="closeCustomer"></Customer>
    </BaseDialog>
    <!-- 发票登记 -->
    <BaseDialog title="发票登记" :visible.sync="showRegister" destroyOnClose width="300px" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto' }">
      <RegisterModel :resData="this.selectColumns" @reAdd="reAdd()" @close="closeRegister"></RegisterModel>
    </BaseDialog>

    <!-- 入库单明细 -->
    <BaseDialog title="s明细" :visible.sync="showInstock" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto' }">
      <InstockModel :resData="this.getData" :resPar="this.tag" @reAdds="reAdds()" @close="closeInstock"></InstockModel>
    </BaseDialog>
  </div>
</template>

<script>
import moment from 'moment';
import { mapState } from 'vuex';
import { dictionary } from '@/utils/dictMixin';
import { exportExcelFile } from '@/utils/index';
import Customer from '@/pages/part/partOutbound/partSales/customer';
import RegisterModel from './registerModel';
import InstockModel from './instockModel';
import { queryInvoiceRegister, registerMoney, cancelDetail, excel } from '@/api/finance/partFinance/invoiceRegister';
// 校验发票的号码
const validatorBillNumber = (rule, value, callback) => {
  if (value.length !== 8) {
    return callback(new Error('字符长度为8'));
  } else {
    callback();
  }
};
export default {
  name: 'InvoiceRegister',
  components: {
    Customer,
    RegisterModel,
    InstockModel
  },
  mixins: [dictionary],
  data() {
    this.BaseTable = null;
    return {
      getData: [],
      topFilterList: this.createTopFilterList(), // 查询字段
      columns: this.createTableColumns(), // 列表字段
      selectColumns: [],
      cancelButton: true,
      all: [], // 表格返回的数据
      feesSettlementList: this.createFeesSettlementList(),
      cancelRegisterAble: false, // 取消登记
      exportAble: false, // 导出
      showCustomerDealer: false, // 是否显示客户
      showRegister: false, // 是否显示登记
      showInstock: false, // 是否显示入库单明细
      registerMoneyYes: '', // 金额统计已合计
      registerMoneyNo: '', // 金额统计为未合计
      fetchParams: { xhrAbort: true },
      fetchApi: queryInvoiceRegister,
      tag: []    // 查询参数
    };
  },
  computed: {
  },
  watch: {

  },
  created() { },
  mounted() {
    // this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    createTopFilterList() {
      let that = this;
      return [
        {
          type: 'RANGE_DATE',
          fieldName: 'starTime|endTime',
          initialValue: [
            moment(
              moment()
                .month(moment().month())
                .startOf('month')
                .valueOf()
            ).format('YYYY-MM-DD'),
            moment(
              moment()
                .month(moment().month())
                .endOf('month')
                .valueOf()
            ).format('YYYY-MM-DD')
          ],
          placeholder: '选择日期',
          valueFormat: 'yyyy-MM-dd',

          labelOptions: {
            initialValue: '12151001',
            fieldName: 'tag',
            itemList: [
              {
                text: '采购入库',
                value: '12151001'
              },
              {
                text: '调拨入库',
                value: '12151002'
              },
              {
                text: '调拨出库',
                value: '12151010'
              }
            ],
            change: async (val) => {
              // 获取表单当前的数据
              const [err, data] = await this.$refs.topFilterForm.GET_FORM_DATA();
              if (err) return;
              that.changeHandle(data);
            }
          }
        },
        {
          type: 'INPUT',
          label: '客户名称',
          fieldName: 'customerName',
          placeholder: '客户名称',
          // readonly: true,
          unitRender: props => {
            return (
              <div>
                <i slot="suffix" style="line-height: 30px" class="el-input__icon el-icon-circle-plus" onClick={() => this.openCustomerDealer()}></i>
              </div>
            );
          }
        },
        {
          type: 'SELECT',
          label: '是否登记',
          fieldName: 'payOff',
          placeholder: '请选择',
          itemList: this.createDictList('1004')
        },
        {
          type: 'INPUT',
          label: '发票号码',
          fieldName: 'bill',
          placeholder: '发票号码',
          // rules: [{ validator: validatorBillNumber, trigger: 'blur' }]
        },
        {
          type: 'RANGE_DATE',
          label: '登记日期',
          fieldName: 'beginDate|endDate',
          placeholder: '选择日期'
        },
        {
          type: 'INPUT',
          label: '备注',
          fieldName: 'remark',
          placeholder: '备注'
        }
      ];
    },
    // 列表字段
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 150,
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.detail(props.row)}>
                  明细
                </el-button>
              </div>
            );
          }
        },
        {
          title: '入库单号',
          dataIndex: 'STOCK_IN_NO',
          width: 150,
          sorter: true
        },
        {
          title: 'ID',
          dataIndex: 'ID',
          width: 150,
          sorter: true,
          disabled: true
        },
        {
          title: '完成/入账日期',
          dataIndex: 'FINISHED_DATE',
          width: 150,
          sorter: true
        },
        {
          title: '供应商代码',
          dataIndex: 'CUSTOMER_CODE',
          width: 150,
          sorter: true
        },
        {
          title: '供应商名称',
          dataIndex: 'CUSTOMER_NAME',
          width: 150,
          sorter: true
        },
        {
          title: '项目数',
          dataIndex: 'ITEM_COUNT',
          width: 150,
          sorter: true,
          render: props => {
            return <span>{1}</span>;
          }
        },
        {
          title: '总金额',
          dataIndex: 'TOTAL_AMOUNT',
          width: 150,
          sorter: true
        },
        {
          title: '含税金额',
          dataIndex: 'BEFORE_TAX_AMOUNT',
          width: 150,
          sorter: true
        },
        {
          title: '是否登记',
          dataIndex: 'IS_PAYOFF_FINANCE',
          width: 150,
          sorter: true,
          render: props => {
            return <span>{props.row.INVOICE_NO != null ? '是' : '否'}</span>;
          }
        },
        {
          title: '发票号',
          dataIndex: 'INVOICE_NO',
          width: 150,
          sorter: true
        },
        {
          title: '登记税率',
          dataIndex: 'TAX',
          width: 150,
          sorter: true
        },
        {
          title: '登记日期',
          dataIndex: 'INVOICE_DATE',
          width: 150,
          sorter: true
        },
        // {
        //   title: '备注',
        //   dataIndex: 'REMARK',
        //   width: 150,
        //   sorter: true,
        //   render: props => {
        //     return <el-input v-model={props.row.RECEIVE_REMARK} placeholder="请输入内容"></el-input>;
        //   }
        // },
        {
          title: '已登记含税金额',
          dataIndex: 'RECORD_IN_AMOUNT',
          width: 150,
          sorter: true
        },
        {
          title: '未登记含税金额',
          dataIndex: 'NOT_RECORD_AMOUNT',
          width: 150,
          sorter: true,
          render: props => {
            return <span>{props.row.RECORD_IN_AMOUNT > 0 ? 0 : props.row.BEFORE_TAX_AMOUNT}</span>;
          }
        }
      ];
    },
    // 统计
    createFeesSettlementList() {
      return [
        {
          type: 'INPUT',
          label: '已登记含税金额合计',
          width: '600px',
          fieldName: 'F_PAY_OFF_AMOUNT_COUNT',
          initialValue: '0',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '未登记含税金额合计',
          width: '600px',
          fieldName: 'TOTAL_AMOUNT_COUNT',
          initialValue: '0',
          disabled: true
        }
      ];
    },
    getAll(val) {
      if (val.length) {
        this.all = val;
        let totalAmount = val[0].TOTAL_AMOUNT_COUNTSS
        // 如果已经金额为空显示0
        if (this.registerMoneyYes == null) {
          this.feesSettlementList.find(x => x.fieldName === 'F_PAY_OFF_AMOUNT_COUNT').initialValue = 0
        } else {
          this.feesSettlementList.find(x => x.fieldName === 'F_PAY_OFF_AMOUNT_COUNT').initialValue = this.registerMoneyYes
        }
        if (this.registerMoneyNo == null) {
          this.feesSettlementList.find(x => x.fieldName === 'TOTAL_AMOUNT_COUNT').initialValue = 0
        } else {
          this.feesSettlementList.find(x => x.fieldName === 'TOTAL_AMOUNT_COUNT').initialValue = this.registerMoneyNo
        }
        this.feesSettlementList = [...this.feesSettlementList]
        // this.countAmount();
      }
    },
    // 选择客户关闭
    closeCustomer() {
      this.showCustomerDealer = false;
    },
    // 计算金额
    countAmount() {
      let payOff = 0;
      let noPayOff = 0;
      this.all.forEach(x => {
        payOff += x.TOTAL_AMOUNT;
        noPayOff += x.TAX_AMOUNT;
      });
    },
    // 发票登记弹窗 点击确定
    async reAdd() {
      this.showRegister = false;
      const [err, data] = await this.$refs.topFilterForm.GET_FORM_DATA();
      if (err) return;
      this.changeHandle(data)
    },
    // 打开供应商弹框
    openCustomerDealer() {
      this.showCustomerDealer = true;
    },
    // 删除供应商销商
    delCustomerDealer() {
      // this.customerComplaint.purchasedDealerCode = '';
      // this.formList1[12].initialValue = '';
      // this.formList1 = [...this.formList1];
    },
    // 供应商数据赋值
    getCustomerInfo(x) {
      this.showCustomerDealer = false;
      this.topFilterList.map(item => {
        if (item.fieldName == 'customerCode') {
          item.initialValue = x[0].CUSTOMER_CODE;
        } else if (item.fieldName == 'customerName') {
          item.initialValue = x[0].CUSTOMER_NAME;
        } else {
          return;
        }
      });
    },
    // 搜索
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val, { xhrAbort: false });

      // 查询后台计算的已登记和未登记金额
      registerMoney(this.fetchParams).then(res => {
        this.registerMoneyYes = res.data[0].registerYes
        this.registerMoneyNo = res.data[0].registerNo
      });
      this.tag = this.fetchParams
    },
    // 明细
    detail(val) {
      this.getData = [val]
      this.showInstock = true;
    },
    //
    onRowSelectChange() {
    },

    // 登记1
    registerClick() {
      if (this.selectColumns.length === 0) {
        this.$message.warning('请选择表格数据');
        return;
      }

      if (this.selectColumns[0].INVOICE_NO != null) {  // 发票号必填，有值就不能登记
        this.$message.warning('不能重复登记');
        return;
      }
      this.showRegister = true;

    },
    // 取消登记
    async cancelRegister() {
      if (this.selectColumns[0].INVOICE_NO === null) {
        alert("没登记不能取消")
      } else {
        let id = this.selectColumns[0].STOCK_IN_NO
        const res = await cancelDetail({ id: id })
        console.log(res);
        if (res.data == 1) {
          this.$notify.success({ title: '提示信息', message: '取消成功!' });
        } else {
          this.$notify.error({ title: '提示信息', message: '取消出错' });
        }
        const [err, data] = await this.$refs.topFilterForm.GET_FORM_DATA();
        if (err) return;
        this.changeHandle(data)
      }

    },
    // 关闭登记
    closeRegister(val) {
      this.showRegister = val
    },
    // 关闭明细
    closeInstock() {
      this.showInstock = false
    },
    // 导出
    async exportTable() {

      const [err, data] = await this.$refs.topFilterForm.GET_FORM_DATA();
      if (err) return;
      console.log("导出参数")
      console.log("data")
      excel(data).then(res => {
        exportExcelFile(res, '发票登记');
      });
    }
  }
}
</script>
<style lang="less" scoped>
.vehicle-details-wrap {
  position: relative;
  margin-top: 20px;
  padding-bottom: @modulePadding;
  .box {
    border: 1px solid #ccc;
    padding-top: 15px;
    padding-right: 15px;
    border-radius: @borderRadius;
    margin-bottom: 20px;
    box-shadow: @boxShadow;
  }

  .choose-style {
    color: @primaryColor;
  }
}
</style>
